dojo.provide("dojot.comment.Comment");
dojo.experimental("dojot.comment.Comment");
dojo.require("dojox.dtl.html");
dojo.require("dojox.dtl.Context");
dojo.require("dojot.util.MemoryPageList");
dojo.require("dojo.i18n");
dojo.require("dijit._Widget");
dojo.require("dojox.dtl._DomTemplated");
dojo.requireLocalization("dojot", "common");
dojo.requireLocalization("dojot", "comment");

var picCommentTemplate = {data: { 
	"identifier": "picId",
	"items": []
}}
dojo.declare("dojot.comment.Comment", [dijit._Widget, dojox.dtl._DomTemplated],
    {
        //模板是否嵌入widet
        widgetsInTemplate: true,
        //相册id
	albumId:0,
        //图片id
	picId:0,
        //todo 
	reviewNode:null,
        //评论内容的store
	commentsStore:null,
        //评论的list
	items:[],
        //国际化的属性文件内容
	_messages:null,
        //评论的textArea对话框
	commentTextArea:null,
        //获取评论列表的url
	commentListUrl:"",
        //post评论的url
	addCommentUrl:"",
        //删除评论的url
	delCommentUrl:"",
        //提交评论的那个button.
	submitBtnId:"submitCommentBt",
        //输入空评论的错误信息。现在在考虑如何处理下面的错误信息。感觉现在这样写有点不太好。
        //因为每次添加新的错误逻辑的时候，需要修改源代码。看看如果扩展这些逻辑吧
	emptyCommentErrorInfo:"",
	overlengthCommentErrorInfo:"",
	forbiddenCommentErrorInfo: "",
	errorInfo:"",
        //查看当前评论的用户userId
	viewId:"",
        //评论所属人的userId
	ownerId:"",
        //是否是管理员
	isAdmin:false,
        
        //删除评论
        deleteComment:"",
        templatePath:dojo.moduleUrl("dojot.comment", "resources/comment.html"),

        postMixInProperties: function(){
            //初始化.在这个函数里面我们主要用来对属性值的设置操作。
            var that = this;
            
            this.commentTextArea = dojo.byId(obj.textAreaId);
            this.commentsStore = new dojo.data.ItemFileWriteStore(picCommentTemplate);
          
            
            //i18n 
            var messages1= dojo.i18n.getLocalization("dojot", "common",dojo.locale);
            var messages2= dojo.i18n.getLocalization("dojot", "comment",dojo.locale);
            this._messages = dojo.mixin({},messages1,messages2);
            
            var commentTemplate = this.templatePath || this.templateString;
            
            this.tpl = new dojox.dtl.Template(commentTemplate);

            //国际化错误信息
            dojo.forEach(["emptyCommentErrorInfo","overlengthCommentErrorInfo","errorInfo","forbiddenCommentErrorInfo","deleteComment"], function(prop){
                    if(!this[prop]){ this[prop] = this._messages[prop]; }
            }, this);
            
            
        },
        postCreate: function(){
            //所有的时间绑定。都在这里做啊。
            //TODO  初始化其他widget,目前只有分页widget
            dojo.connect(dojo.byId(this.submitBtnId), "onclick", dojo.hitch(this,"_addCommentToServer"));
              //增加删除评论函数到全局变量中。
            dojo.global["deleteComment"] = dojo.hitch(this,"_deleteCommentToServer");
            
            this.pageList = new dojot.util.PageList_widget({},this.pageInfo);

        },
	showAllComments: function(picId){
            //根据图片id去获得所有的评论。
            console.log("showAllComments-----------》"+picId+this.commentListUrl);
            this.picId = picId;
            var that = this;
            //这里面的item是一个对象。里面包括了所有的评论列表,和图片的一些相关信息
            //比如图片上传时间，评论数，图片浏览数。所以我们的评论列表只是其中的一点点。
            var _handleItem = function(item){
                //如果在仓库找到了则显示,没有则从服务器去拿
                if(items){
                        that._showItem(item);
                }else{
                    dojo.xhrGet({
                        url: that.commentListUrl+"?picId="+picId,
                        load:_loadItems,
                        error:dojo.hitch(that,"_errorHandler"),
                        handleAs: "json"
                    });
                }
            };
            var _loadItems = function(items){
                that._addItemToStore(items,this._showItem);
            };
            var req = {
                identity:picId,
                onItem:_handleItem,
                onError:that._errorHandler
            };
            this.commentsStore.fetchItemByIdentity(req);
	},
	_addItemToStore: function(item,showItem){
            if(item){
                var newItem  = this.commentsStore.newItem(item);
                this.commentsStore.save();
                this._showItem(newItem);
            }	
	},
	_errorHandler: function(data){
            this.toggleTextArea(false);
            if(data &&  data.status == 403){
                    this.suggestInfo(this.forbiddenCommentErrorInfo);
            }else{
                    this.suggestInfo(this.errorInfo);
            }
            return;
	},
	_showItem: function(item){
            this.currentCommentItem = item;
            //add broswerCount
            this.addBroswerCountToStore(item);
            this.tplContext = new dojox.dtl.Context(item);
            this._setPageInfo();
            this._render();
		//dojo.fadeIn({node:reviewNode}).play(50); 
	},
	addBroswerCountToStore:function(item){
            var broswerCount = this.commentsStore.getValue(item,"browseCount");
            this.commentsStore.setValue(item,"browseCount",parseInt(broswerCount)+1);
            this.commentsStore.save();
	},
	_addCommentToServer: function(){
            var isEmpty = this.commentTextArea.value.isEmpty();
            if(isEmpty){
                    this.suggestInfo(this.emptyCommentErrorInfo);
                    return;
            }
            var value = this.commentTextArea.value.trim;
            if(value.length > 50){
                    this.suggestInfo(this.overlengthCommentErrorInfo);
                    return;
            }
            this.toggleTextArea(true);
            var that = this;
            dojo.xhrPost({
                url: that.addCommentUrl,
                content:{
                        picId:that.picId,
                        desc:value,
                        userId:that.viewId
                },
                load:function(data){
                        console.log(data);
                        that._addCommentToClient(data);
                },
                error:dojo.hitch(that,"_errorHandler"),
                handleAs: "json"
            });	
		
	},
	_addCommentToClient: function(comment){
		//add comment
            this.changeComment(function(comments){
                    comments.splice(0,0,comment);
            },1)
            this.toggleTextArea(false);
	},
	_deleteCommentToServer: function(cId){
            if(confirm(this._messages.confirmDelete)){
                var that = this;
                dojo.xhrPost({
                        url: that.delCommentUrl,
                        content:{
                                commentId: cId
                        },
                        load:function(data){
                                that._deleteCommentFromClient(cId);
                        },
                        error:that._errorHandler,
                        handleAs: "json"
                });	
            }
		
	},
	_deleteCommentFromClient:function(cId){
            //delete comment
            var that = this;
            this.changeComment(function(comments){
                    var index = that._getCommentIndex(cId,comments);
                    comments.splice(index,1);
            },-1);
	},
	_getUserName:function(){
            initPage();
            showPortrait('.portraitThumbComment','spic');
	},
	changeComment:function(fn,count){
            var comments = this.commentsStore.getValues(this.currentCommentItem,"picCommentList");
            //deal with comment, add or delete	
            fn(comments);
            this.commentsStore.setValues(this.currentCommentItem,"picCommentList",comments);
            //add comment count to store
            var commentCount = this.commentsStore.getValue(this.currentCommentItem,"commentCount");
            commentCount = parseInt(commentCount) + count;
            this.commentsStore.setValue(this.currentCommentItem,"commentCount",commentCount);
            //save
            this.commentsStore.save();
            this.tplContext.picCommentList = comments;
            this.tplContext.commentCount = commentCount;
            this._setPageInfo();
            this._render();
            this.commentTextArea.value = "";
	},
	_setPageInfo:function(){
            var req = {
                    items:this.tplContext.picCommentList,
                    isMemoryPage: true
            };
            var pageList = new dojot.util.MemoryPageList(req);
            console.log(pageList);
    
            this.tplContext.pageList = pageList;
	},
	_render:function(){
		
            dojo.publish("showPicExtraInfo",[this.tplContext]);
            //i18n
          
            //替换 amp 到 & 是因为在dojox.dtl 里面的.base的js的650行进行了替换，所以要替换回来
            templateString = templateString.deentityify().replace(/(<br\/>){1,}/g,"<br/>");

            this.reviewNode.innerHTML = templateString;
            this._getUserName();
            
            //初始用户访问控制显示
            dojot.security.isAccess("review");
	},
	_getCommentIndex:function(cId,comments){
            var i = 0;
            var com;
            for(var index in comments){
                    com = comments[index];
                    if(com.id == cId)return i;
                    i++;
            }
            return undefined;
	},
	showPage: function(index){
            this.tplContext.pageList.showIndex(index);
            this._render();
	},
	toggleTextArea:function(flag){
            if(flag){
                    dojo.attr(this.commentTextArea,"disabled",true)
            }else{
                    dojo.attr(this.commentTextArea,"disabled",false)
            }
            //var attrDisabbled = dojo.attr(this.commentTextArea,"disabled");
            //attrDisabbled ?  dojo.attr(this.commentTextArea,"disabled",false) : dojo.attr(this.commentTextArea,"disabled",true);
            if(dojo.attr(this.commentTextArea,"disabled")){
                console.log("attrDisabbled");
                dojo.style(this.commentTextArea , "background","#ffffe0");
            }else{
                console.log("attrDisabbled fale");
                dojo.style(this.commentTextArea , "background","#ffffff");
            }
	},
	suggestInfo:function(value){
            var node = dojo.byId("suggestInfo");
            node.innerHTML = value;
            var fadeIn = dojo.fx.wipeIn({
                    node: node,
                    duration: 500
            });
            var dadeOut = dojo.fadeOut({
                    node: node,
                    duration: 1000
            });
            
            var a1 = dojo.fx.chain([fadeIn, dadeOut]);
            
            dojo.connect(a1, "onBegin", function(){
                    console.log("onBegin");
                    dojo.style("suggestInfo", "opacity",1);
                    console.log(dojo.byId("commentErrorInfo"));
            });
            a1.play();
	},
	//清空评论的内容,如果图片被删除，或者图片被转移走，我们需要清空这张图片的所有评论,就是从仓库里面删除我们的数据
	//这步其实可以不做，但是为了节省空间，先加上
	cleanComment: function(picId){
		var that = this;
		var _deleteItem = function(item){
			if(item){
				that.commentsStore.deleteItem(item);
				that.commentsStore.save();
			}
		}
		var req = {
			identity:picId,
			onItem:_deleteItem,
			onError:that._errorHandler
		};
		this.commentsStore.fetchItemByIdentity(req);
		this.reviewNode.innerHTML = "";
	}
});
